const util = require('../util/util');
Page({
  data: {
    imgs: [],
    sugg_media: [],
    sugg_name: '',
    sugg_site: '', // 事件发生位置
    sugg_location: '',
    sugg_text: '', // 问题描述
    sugg_user_tele: '',
    sugg_sub_id: '',
    sugg_file: [],
    sugg_media_type: 1,
    sugg_filePath: '',
    sugg_title: '',
    sugg_treat: 0, // 默认不需要回访
    sugg_chart_id: '',
    maxWord: 200,
    currentWord: 0
  },

  onShow: function() {
    const app = getApp();
    this.setData({
      reupload_flag: app.globalData.reupload_flag,
      times: app.globalData.times
    });
    console.log("onShow_reupload_flag:", this.data.reupload_flag);
    console.log("onShow_times:", this.data.times);

    // 如果需要，启动计时器
    if (this.data.reupload_flag == '1') {
      app.startTimer();
    }
  },

  handleInputText: function(e) {
    var that = this;
    var wordLength = parseInt(e.detail.value.length);
    if (that.data.maxWord < wordLength) {
      return;
    }
    that.setData({
      sugg_text: e.detail.value,
      currentWord: wordLength
    });
  }
,  

  handleInputLocation: function(e) {
    this.setData({
      sugg_site: e.detail.value
    });
  },

  limitWord: function(e) {
    var that = this;
    var value = e.detail.value;
    var wordLength = parseInt(value.length);
    if (that.data.maxWord < wordLength) {
      return;
    }
    that.setData({
      currentWord: wordLength
    });
  },

  chooseLocation: function() {
    var that = this;
    wx.chooseLocation({
      success: function(res) {
        that.setData({
          sugg_site: res.address + res.name // 使用返回的地址信息填入 sugg_site
        });
      },
      fail: function(err) {
        wx.showToast({
          title: '获取位置失败，请重试',
          icon: 'none'
        });
      }
    });
  },

  handleChooseImg: function() {
    var that = this;
    wx.chooseMedia({
      count: 9,
      mediaType: ['image', 'video'],
      sourceType: ['album', 'camera'],
      sizeType: ['original', 'compressed'],
      camera: 'back',
      success(res) {
        var tempFiles = res.tempFiles;
        for (var i = 0; i < tempFiles.length; i++) {
          that.setData({
            imgs: [...that.data.imgs, tempFiles[i].tempFilePath],
            sugg_filePath: [...that.data.sugg_filePath, tempFiles[i].tempFilePath]
          });
        }
      }
    });
  },

  startSetInter: function(e) {
    const app = getApp();
    this.setData({
      reupload_flag: app.globalData.reupload_flag,
      times: app.globalData.times
    });

    if (this.data.reupload_flag == '1') {
      if (this.data.times >= 180) { // 如果计数器达到 180 秒
        console.log("已经达到3min", this.data.times);
        app.stopTimer(); // 停止全局计时器
        this.setData({ // 更新数据
          reupload_flag: 0,
          times: 0,
        });
      }
    } else {
      this.setData({ // 更新数据
        reupload_flag: 1,
        times: 0, // 初始化计时器的计数器
      });
      app.startTimer(); // 启动全局计时器
      console.log("reupload_flag:", this.data.reupload_flag);
      console.log("现在开始计数3min");
    }
  },

  deleteImg: function(e) {
    var that = this;
    wx.showModal({
      title: "提示",
      content: "是否删除",
      success: function(res) {
        if (res.confirm) {
          that.data.imgs.splice(e.currentTarget.dataset.index, 1);
          that.setData({
            imgs: that.data.imgs
          });
        }
      }
    });
  },

  chooseTreat: function(e) {
    const selectedTreat = e.currentTarget.dataset.treat;
    this.setData({
      sugg_treat: selectedTreat
    });
  },
  handleInputSite: function(e) {
    this.setData({
      sugg_site: e.detail.value, // 更新事件发生位置
    });
  },

  // 处理详细地址
  handleInputLocation: function(e) {
    this.setData({
      sugg_location: e.detail.value, // 更新详细地址
    });
  },
  checkPhoneNum: function(phoneNumber) {
    if (!/^1[3456789]\d{9}$/.test(phoneNumber)) {
      return false;
    }
    return true;
  },

  findEmptyKeys: function(jsonObj) {
    return Object.keys(jsonObj).filter(key => !jsonObj[key] || jsonObj[key] === '');
  },

  formsubmit: function(e) {
    var that = this;
    const formData = e.detail.value;
    console.log(formData); // 检查提交的数据，确保有 sugg_site 和 sugg_text
  
    const judge = this.findEmptyKeys(formData);
    if (judge.includes("sugg_name") || judge.includes("sugg_user_tele") || judge.includes("sugg_title") || judge.includes("sugg_text") || judge.includes("sugg_site")) {
      wx.showModal({
        title: '提示',
        content: '请完成所有必填项！',
        showCancel: false,
      });
    } else {
      if (!this.checkPhoneNum(formData.sugg_user_tele)) {
        wx.showModal({
          title: '提示',
          content: '手机号不正确，请检查！',
          showCancel: false,
        });
      } else {
        // 拼接 sugg_site 和 sugg_location
        let finalSite = formData.sugg_site + " " + formData.sugg_location;
  
        this.setData({
          sugg_media: formData.sugg_media,
          sugg_name: formData.sugg_name,
          sugg_site: finalSite, // 更新为拼接后的 sugg_site
          sugg_text: formData.sugg_text, // 上传描述
          sugg_user_tele: formData.sugg_user_tele,
          sugg_title: formData.sugg_title,
          sugg_location: formData.sugg_location,
        });
  
        console.log({
          'sugg_name': this.data.sugg_name,
          'sugg_site': this.data.sugg_site, // 拼接后的 sugg_site
          'sugg_text': this.data.sugg_text,
          'sugg_user_tele': this.data.sugg_user_tele,
          'sugg_sub_id': wx.getStorageSync('id'),
          'sugg_title': this.data.sugg_title,
          'sugg_treat': this.data.sugg_treat,
          'sugg_location': this.data.sugg_location,
        });
  
        wx.request({
          url: 'https://api.kuangqiaodongjie.cn/user/SuggestionUser/',
          method: 'POST',
          header: {
            'Authorization': wx.getStorageSync('token'),
            "content-type": 'application/x-www-form-urlencoded',
          },
          data: {
            'sugg_name': this.data.sugg_name,
            'sugg_site': this.data.sugg_site, // 提交拼接后的 sugg_site
            'sugg_text': this.data.sugg_text,
            'sugg_user_tele': this.data.sugg_user_tele,
            'sugg_sub_id': wx.getStorageSync('id'),
            'sugg_title': this.data.sugg_title,
            'sugg_treat': this.data.sugg_treat,
            'sugg_location': this.data.sugg_location,
          },
          success: function(res) {
            console.log("投诉", res);
            if (res.statusCode == 200) {
              that.setData({
                sugg_chart_id: res.data.data.id,
              });
              // 上传图片
              for (let i = 0; i < that.data.imgs.length; i++) {
                console.log("上传图片：", i);
                wx.uploadFile({
                  url: 'https://api.kuangqiaodongjie.cn/user/UserSuggestionPicture/' + that.data.sugg_chart_id + '/',
                  filePath: that.data.sugg_filePath[i],
                  name: "sugg_media",
                  header: {
                    'Authorization': wx.getStorageSync('token'),
                    "content-type": "multipart/form-data",
                  },
                  formData: {
                    'sugg_media': that.data.sugg_filePath[i],
                  },
                  success: function(res) {
                    console.log("投诉图片", res);
                    if (res.statusCode == 200) {
                      // 图片上传成功
                    }
                  },
                  fail: function(err) {
                    console.log(err);
                    wx.showModal({
                      title: '提示',
                      content: '提交失败，请重试！',
                      showCancel: false,
                    });
                  },
                });
              }
              wx.showModal({
                title: '提示',
                content: '提交成功，请耐心等待回复。',
                showCancel: false,
                success: function() {
                  wx.switchTab({
                    url: '../index/index',
                  });
                },
              });
            }
          },
          fail: function(err) {
            console.log(err);
            wx.showModal({
              title: '提示',
              content: '提交失败，请重试！',
              showCancel: false,
            });
          },
        });
      }
    }
  }
,  
  

  pre_formsubmit: function(e) {
    console.log("this.data.reupload_flag:", this.data.reupload_flag);
    if (this.data.reupload_flag == 1) {
      console.log("计时：", this.data.times);
      console.log("ttt2", this.data.reupload_flag);
      wx.showModal({
        title: '提示',
        content: '您在三分钟内已提交过一次表单，是否要再次提交',
        success: (res) => {
          if (!res.confirm) {
            wx.switchTab({
              url: "../index/index"
            });
          } else {
            this.formsubmit(e);
          }
        }
      });
    } else {
      this.formsubmit(e);
    }
  }
});
